<template>
  <div style="width: 100%;height: 100%">
    <div class="map" id="map"></div>
    <div v-if="showPopup === true" class="popup">
      弹窗弹窗弹窗弹窗弹窗弹窗弹窗
    </div>
  </div>
</template>

<script>
import 'ol/ol.css';
import Map from 'ol/Map';
import OSM from 'ol/source/OSM';
import Feature from 'ol/Feature';
import VectorSource from 'ol/source/Vector';
import { Tile as TileLayer, Vector as VectorLayer } from 'ol/layer';
import View from 'ol/View';
import XYZ from 'ol/source/XYZ'
import Point from 'ol/geom/Point';
import { Fill, Style, Circle } from 'ol/style'
import { getDataCenterPoint } from "@/api/map";
import { defaults as defaultControls } from 'ol/control';

export default {
  name: "openlayersMap",
  data() {
    return {
      mapObj: null,
      mapDom: null,
      mapPointList: [],
      pointLayerSource: null,
      pointLayer: null,
      pointData: [],

      showPopup: false,
      popupContent: '',
      selectedFeature: null
    }
  },
  mounted() {
    this.getMap()
    this.initMap()
    // this.addPoint()
    //     this.mapObj.on('singleclick', (event) => {
    //       console.log(event)
    //       var pixel = event.pixel;
    //       console.log(pixel)
    //       var featurelist = this.pointLayerSource.getFeatures();
    //       console.log(featurelist)
    //       this.mapObj.forEachFeatureAtPixel(pixel, function (feature, layer) {
    //         console.log(feature)
    //         if (feature){
    //           var featureId = feature.getId();
    //           var coordinates = feature.getGeometry().getCoordinates();
    //           console.log(featureId)
    //           console.log(coordinates)
    //         }
    //         else{
    //           console.log('Feature not found');
    //         }
    //       });

    // // // 获取特定feature
    // // var feature = this.pointLayerSource.getFeatures()[0]; // 假设我们获取第一个feature
    // //  console.log(feature)
    // // // 获取feature的ID
    // // var featureId = feature.getId();
    // // console.log(featureId)
    //       // var feature = this.pointLayerSource.getFeatureById('456789');
    //       // console.log(feature)
    //       // if (feature){
    //       //   console.log("Feature found:", feature.getGeometry().getcoordinates())
    //       //   console.log("Feature name:",feature.get( id ));
    //       // }
    //       // else{
    //       //   console.log('Feature not found');
    //       // }

    //       // console.log('event', event);
    //       // console.log('Map clicked at:', event.pixel);
    //       // // this.mapClickHandler(event);
    //       // var pixel = this.mapObj.getEventPixel(event.originalEvent);
    //       // console.log(this.mapObj);
    //       // var _feature = this.mapObj.forEachFeatureAtPixel(pixel, function (_feature) {

    //       //   return _feature;
    //       // });

    //       // if (_feature) {
    //       //   // 你点击的feature现在在变量feature中，你可以对它进行操作
    //       //   console.log(2);
    //       //   console.log(_feature);
    //       //   let id = _feature.getId()
    //       //   console.log(id)
    //       // }
    //       // else {
    //       //   console.log(3);
    //       //   console.log(_feature);
    //       // }
    //     });
  },
  methods: {
    // 获取后台数据
    getMap() {
      // 获取点位数据
      getDataCenterPoint().then((res) => {
        if (res.code === 200) {
          // console.log('res', res);
          this.pointData = res.data
          // 加载地理坐标
          this.addPoint()
        }
      })
    },

    // 清除地图 某些情况 地图容器会存在两个 导致地图无法正常显示 这个问题折腾了我半天。
    // 找了半天官方貌似也没有提供 对应的 api，自己动手了。
    mapClear() {
      if (this.mapDom) {
        this.mapDom.innerHTML = ''
        this.mapDom = null
      }
    },

    // 初始化地图
    initMap() {
      // 先尝试清除
      this.mapClear()
      // 获取地图容器
      this.mapDom = document.getElementById('map')
      // 初始化地图配置
      this.mapObj = new Map({
        target: this.mapDom, // 地图容器
        view: new View({
          zoom: 5.3, // 缩放
          projection: 'EPSG:4326', // 坐标系
          center: [120.990969, 32.635013], // 地图中心点
        }),
        //加载控件到地图容器中
        controls: defaultControls({
          zoom: false,
          rotate: false,
          attribution: false
        }),
      })
      // 添加一个使用离线瓦片地图的层
      const offlineMapLayer = new TileLayer({
        className: "baseLayerClass",
        source: new XYZ({
          // url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
          url: "https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetPurplishBlue/MapServer/tile/{z}/{y}/{x}",
        })
        // source: new OSM()	//OSM地图
      })
      // 将图层添加到地图
      this.mapObj.addLayer(offlineMapLayer)
    },

    // 添加地理坐标
    addPoint() {
      // this.delPointAll()
      // console.log(this.pointData)
      // const convertedArray = this.pointData.map(item => {
      //   console.log('item', item.longitude !== null);
      //   if (item.longitude !== null) {
      //     ({
      //       longitude: item.longitude,
      //       latitude: item.latitude
      //     })
      //   }
      // });


      const convertedArray2 = [
        { longitude: 118.150, latitude: 34.030 },
        { longitude: 120.210, latitude: 31.850 },
        { longitude: 117.380, latitude: 36.120 },
        { longitude: 116.280, latitude: 32.150 },
        { longitude: 117.260, latitude: 29.660 },
      ]
      // console.log('convertedArray', convertedArray);
      // console.log('convertedArray2', convertedArray2);

      convertedArray2.map(item => {
        // 创建点
        const point = new Feature({
          // geometry: new Point([item.id, item.longitude, item.latitude]),
          geometry: new Point([item.longitude, item.latitude]),
          data: item,
          // name:'My point',
          // id:'123456'
          // id: item.id
        })
        // point.setId(item.id)
        // 点的样式
        const iconStyle = new Style({
          // image: new Icon({
          //   color: '#ffffff',
          //   crossOrigin: 'anonymous',
          //   src: this.markerIcon,
          // }),
          image: new Circle({
            radius: 10,
            fill: new Fill({
              color: "#0D98BA"
            })
          })
        })
        // console.log('point',point);s
        // 设置样式
        point.setStyle(iconStyle)
        // 保存到数据  方便删除
        this.mapPointList.push(point)
        // console.log('point',point)
      })
      // console.log('this.mapPointList', this.mapPointList);

      // 创建geojson据源
      this.pointLayerSource = new VectorSource({ features: this.mapPointList })
      // 创建图层 并加载数据
      this.pointLayer = new VectorLayer({ source: this.pointLayerSource })
      // 将图层添加地图上
      this.mapObj.addLayer(this.pointLayer)

    },

    // 地理点位删除
    // delPointAll() {
    //   // 判断 删除的数据源是否存在
    //   if (this.pointLayerSource) {
    //     // 遍历删除
    //     this.mapPointList.map(item => {
    //       this.pointLayerSource.removeFeature(item)
    //     })

    //     // 删除图层 重置数据
    //     this.mapObj.removeLayer(this.pointLayer)
    //     this.pointLayerSource = null
    //     this.pointLayer = null
    //     this.mapPointList = []
    //   }
    // },

    mapClickHandler(event) {
      let _that = this
      // 使用 `forEachFeatureAtPixel` 方法来获取点击位置处的地图要素（feature）
      // console.log('event', event);
      // console.log('Map clicked at:', event.pixel);
      // debugger
      console.log(_that.mapObj)
      const feature = _that.mapObj.forEachFeatureAtPixel(event.pixel, function (feature) {
        return feature;
      });
      // console.log('feature', feature);


      // 检查获取到的要素是否存在并且其几何类型是否为 'Point'
      if (feature && feature.getGeometry().getType() === 'Point') {
        // 设置 `showPopup` 为 true，以显示弹出窗口
        _that.showPopup = true;
        console.log('_that.showPopup', _that.showPopup);

        // 保存选中的要素
        _that.selectedFeature = feature;

        // 设置弹出窗口的内容，显示经度和纬度信息
        _that.popupContent = `经度: ${feature.get('data').longitude}, 纬度: ${feature.get('data').latitude}`;
      } else {
        // 如果没有找到要素或者要素类型不是 'Point'，则隐藏弹出窗口并清除选中要素
        _that.showPopup = false;
        // console.log('_that.showPopup123123', _that.showPopup);

        _that.selectedFeature = null;
      }
    },

  },
  beforeDestroy() {
    this.mapClear()
  },
}

</script>

<style scoped>
.map {
  width: 100%;
  height: 100%;
}

.popup {
  position: absolute;
  top: 10px;
  left: 10px;
  background: white;
  padding: 10px;
  border-radius: 3px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
</style>
